package com.ydh.host.util;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 接口请求线程切换
 * @author 13001
 */
public class RxJavaNetworkUtils {

    /**
     * 网络请求线程切换（请求：子 ； 返回：主 ）
     *
     * @param observer 回调执行
     * @param <T>
     * @return
     */
    public static <T> ObservableTransformer<T, T> applySchedulers(Observer<T> observer) {
        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> upstream) {
                Observable<T> tObservable = upstream.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
                tObservable.subscribe(observer);
                return tObservable;
            }
        };
    }

    /**
     * 网络请求线程切换（请求：子 ； 返回：子 ）
     *
     * @param observer 回调执行
     * @param <T>
     * @return
     */
    public static <T> ObservableTransformer<T, T> applyAsyncSchedulers(Observer<T> observer) {
        return new ObservableTransformer<T, T>() {
            @Override
            public ObservableSource<T> apply(Observable<T> upstream) {
                Observable<T> tObservable = upstream.subscribeOn(Schedulers.io());
                tObservable.subscribe(observer);
                return tObservable;
            }
        };
    }

}
